class request {
    constructor() {
        this.header = {
            "Content-Type": 'application/json',
            "Accept": 'application/json',
        }
    }

    /**
     * 设置统一的异常处理
     */
    setErrorHandler(handler) {
        this.errorHandler = handler;
    }

    /**
     * GET类型的网络请求
     */
    getRequest(url, data, header = {}) {
        return this.requestAll(url, data, header, 'GET')
    }

    /**
     * POST类型的网络请求
     */
    postRequest(url, data, header = {}) {
        return this.requestAll(url, data, header, 'POST')
    }

    /**
     * PUT类型的网络请求
     */
    putRequest(url, data, header = {}) {
        return this.requestAll(url, data, header, 'PUT')
    }

    /**
     * DELETE类型的网络请求
     */
    deleteRequest(url, data, header = {}) {
        return this.requestAll(url, data, header, 'DELETE')
    }

    upload(url, file, header = {}) {
        return this.requestFile(url, file, header, 'POST');
    }


    /**
     * 图片上传
     */
    requestFile(url, file, header, method) {
        header = header.concat(this.header);
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: url,
                filePath: file,
                name: 'file',
                //header: {'Content-Type': 'multipart/form-data', "X-Auth-Token-Agent": wx.getStorageSync('token') || '' },
                header: header,
                formData: {},
                success: (res => {
                    resolve(res)
                }),
                fail: (res => {
                    if (this.errorHandler != null) {
                        this.errorHandler(res)
                    }
                    reject(res)
                })
            })
        })
    }


    /**
     * 网络请求
     */
    requestAll(url, data, header, method) {
        return new Promise((resolve, reject) => {
            wx.request({
                url: url,
                data: data,
                header: header,
                method: method,
                success: (res => {
                    resolve(res)
                }),
                fail: (res => {
                    if (this.errorHandler != null) {
                        this.errorHandler(res)
                    }
                    reject(res)
                })
            })
        })
    }
}

export default request